package domain.HQLQuery;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

/**
 * 工具类，用于Session的创建和关闭
 */
public class HbmUtil {
    public static SessionFactory sessionFactory;
    static {
        try{
            Configuration configuration = new Configuration().configure();
            ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static final ThreadLocal<Session> session = new ThreadLocal<>();

    public static Session currentSession(){
        Session s = session.get();
        if(s == null){
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void closeSession(){
        Session s = session.get();
        if(s != null){
            s.close();
        }
        session.set(null);
    }

}
